<?php

/* he 全通信息设置和导出
 */

class DefaultController extends FController {

    public $user_school_list;
    public $user_subject_list;
    public $user_role_list;
    public $exam_id;

    //权限
    public function accessRules() {
        $config = array(
            'index' => 1,
            'allproblemuser' => 1,
            'problemaccount' => 1,
            'export' => 1
        );
        return ZRole::auth("role", $config);
    }

    public function __common() {
        parent::init();
        if (empty($this->cLoginUser)) {
            $this->redirect($this->createUrl('/site/login'));
        } else {
            $userLoginUser = $this->cLoginUser;
            $this->user_role_list = isset($userLoginUser['cuser']['role_id']) ? $userLoginUser['cuser']['role_id'] : '';
            $this->user_school_list = isset($userLoginUser['cuser']['school']['school_id']) ? $userLoginUser['cuser']['school']['school_id'] : '';
            $this->user_subject_list = isset($userLoginUser['cuser']['school']['subject_id']) ? $userLoginUser['cuser']['school']['subject_id'] : '';
            $zRow = new ZRole();
            //得到学校对应的考试
            $exam_list = $zRow->_getSchoolExam($this->user_school_list);
            if (!empty($exam_list)) {
                $this->exam_id = implode(',', $exam_list);
            }
        }
        $this->commonScript();
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
    }

    public function actionIndex() {
        $this->__common();
        $this->title = "阅卷教师信息维护";
        $page = (int) $this->request->getParam('page', 1);
        $s['exam_id'] = (int) $this->request->getParam('exam_id');
        $s['subject_id'] = (int) $this->request->getParam('subject_id');
        $s['school_id'] = (int) $this->request->getParam('school_id');
        $s['username'] = (string) $this->request->getParam('username');
        $where = $wh = '';
        if (empty($s['exam_id'])) {
            //权限判断
            if ($this->user_role_list != 1 && !empty($this->exam_id)) {
                $where = ' WHERE "exam_id" IN (' . $this->exam_id . ')';
                $wh = ' AND "exam_id" IN (' . $this->exam_id . ')';
            }
        } else {
            $where = ' WHERE "exam_id" = ' . $s['exam_id'];
        }
        $examall = ZTask::_getExamAll($wh);
        $examdata = new ExamData();
        $zEdu = new ZEdu();
        if ($this->user_role_list != 1) {
            $schoolall = $zEdu->_getSchoolInfo($this->user_school_list);
        } else {
        $schoolall = $examdata->_getSchool();
        }

        if ($this->user_role_list != 1) {//科目权限设定
            $subjectall = $examdata->_getSubjectList($this->user_subject_list);
        } else {
        $subjectall = $examdata->_getSubject();
        }
        $data = ZProblemNum::_getAllproblemnum($s,$this->user_role_list,$this->user_school_list,$this->user_subject_list,$this->exam_id);
	
        if (!empty($data)) {
            foreach ($data['listDatas'] as $key => $one) {
                $num = ZProblemNum::_getAllproblem($one['teacher_id']);
                $examdata = new ExamData();
                $task_exam = ZTask::_getExamOne($one['exam_id']);
                if ($task_exam) {
                    $data['listDatas'][$key]['exam_term_name'] = $task_exam['exam_term_name'];
                } else {
                    $data['listDatas'][$key]['exam_term_name'] = '';
                }
                $data['listDatas'][$key]['num_ids'] = $num;
            }
        }
			
        $pageUrl = $this->createUrl('/problem/default/index', $s);
        $this->render('index', array(
            'pageUrl' => $pageUrl,
            'page' => $page,
            'examall' => $examall,
            'schoolall' => $schoolall,
            'subjectall' => $subjectall,
            'data' => $data['listDatas'],
            'pages' => $data['pages'],
            'search' => $s,
        ));
    }

    /*
     *
     */

    public function actionList() {
        $this->__common();
        $this->title = "阅卷教师帐号维护";
        $page = (int) $this->request->getParam('page', 1);
        $s['exam_id'] = (int) $this->request->getParam('exam_id');
        $s['subject_id'] = (int) $this->request->getParam('subject_id');
        $s['school_id'] = (int) $this->request->getParam('school_id');
        $s['username'] = (string) $this->request->getParam('username');
        $where = $wh = '';
        if (empty($s['exam_id'])) {
            //权限判断
            if ($this->user_role_list != 1 && !empty($this->exam_id)) {
                $where = " WHERE \"exam_id\" IN (" . $this->exam_id . ")";
                $wh = " AND \"exam_id\" IN (" . $this->exam_id . ")";
            }
        } else {
            $where = " WHERE \"exam_id\" = " . $s['exam_id'];
        }
        $examall = ZTask::_getExamAll($wh);
        $examdata = new ExamData();
        $zEdu = new ZEdu();
        if ($this->user_role_list != 1) {
            $schoolall = $zEdu->_getSchoolInfo($this->user_school_list);
        } else {
        $schoolall = $examdata->_getSchool();
        }
        if ($this->user_role_list != 1) {//科目权限设定
            $subjectall = $examdata->_getSubjectList($this->user_subject_list);
        } else {
        $subjectall = $examdata->_getSubject();
        }
        
        $data = ZProblemNum::_getAllproblemnum($s,$this->user_role_list,$this->user_school_list,$this->user_subject_list,$this->exam_id);
        if ($data) {
            foreach ($data['listDatas'] as $key => $one) {
                $num = ZProblemNum::_getAllproblem($one['teacher_id']);
                $task_exam = ZTask::_getExamOne($one['exam_id']);
                if ($task_exam) {
                    $data['listDatas'][$key]['exam_term_name'] = $task_exam['exam_term_name'];
                } else {
                    $data['listDatas'][$key]['exam_term_name'] = '';
                }
                $data['listDatas'][$key]['num_ids'] = $num;
            }
        }

        $pageUrl = $this->createUrl('/problem/default/list', $s);
        $this->render('list', array(
            'pageUrl' => $pageUrl,
            'page' => $page,
            'examall' => $examall,
            'schoolall' => $schoolall,
            'subjectall' => $subjectall,
            'data' => $data['listDatas'],
            'pages' => $data['pages'],
            'search' => $s,
        ));
    }

    /*
     * 阅卷考题教师分配
     */

    public function actionProblemadd() {
        if ($_POST) {
            $teacher = new Teacher();
            $teacherinfo = $teacher->findByPk($_POST['teacher_id']);
            $teacherinfo->leader = isset($_POST['is_group']) ? $_POST['is_group'] : 0;
            if ($teacherinfo->update()) {
                $this->redirect('/problem/default/index');
            }
        }
        $teacher_id = $this->request->getParam('teacher_id');
        $examdata = new ExamData();
        $schoolall = $examdata->_getSchool();
        $teacherinfo = $num = array();
        if ($teacher_id) {
            $teacher = new Teacher();
            $teacherinfo = $teacher->findByPk($teacher_id);
            $teacherinfo = $teacherinfo->attributes;
            $num = ZProblemNum::_getAllproblem($teacher_id);
            $task_exam = ZTask::_getExamOne($teacherinfo['exam_id']);
            if ($task_exam) {
                $teacherinfo['exam_term_name'] = $task_exam['exam_term_name'];
            } else {
                $teacherinfo['exam_term_name'] = '';
            }
        }
        $this->renderPartial("problemadd", array('teacherinfo' => $teacherinfo, 'num' => $num, 'schoolall' => $schoolall), true);
    }

    public function actionAllproblemuseredit() {
        if ($_POST) {
            $teacher = new Teacher();
            $teacherinfo = $teacher->findByPk($_POST['teacher_id']);
            $teacherinfo->teacher_num = $_POST['problemadd'];
            $teacherinfo->teacher_pswd = $_POST['teacher_pswd'];
            if ($teacherinfo->update()) {
                $this->redirect('/problem/default/list');
            }
        }
        $teacher_id = $this->request->getParam('teacher_id');
        $examdata = new ExamData();
        $schoolall = $examdata->_getSchool();
        $teacherinfo = $num = array();
        if ($teacher_id) {
            $teacher = new Teacher();
            $teacherinfo = $teacher->findByPk($teacher_id);
            $teacherinfo = $teacherinfo->attributes;
            $num = ZProblemNum::_getAllproblem($teacher_id);
            $task_exam = ZTask::_getExamOne($teacherinfo['exam_id']);
            if ($task_exam) {
                $teacherinfo['exam_term_name'] = $task_exam['exam_term_name'];
            } else {
                $teacherinfo['exam_term_name'] = '';
            }
        }
        $this->renderPartial("allproblemuseredit", array('teacherinfo' => $teacherinfo, 'num' => $num, 'schoolall' => $schoolall), true);
    }

    //删除阅卷教师信分题
    public function actionDeleteproblem() {
        $teacher_id = (int) $this->request->getParam('teacher_id');
        $teacher = new Teacher();
        if ($teacher->deleteByPk($teacher_id)) {
            echo 1;
        } else {
            echo 2;
        }
    }

    //全通帐号生成页面
    public function actionAllproblemuser() {
        $ch = $this->request->getParam('ch');
        $username = '';
        if ($ch) {
            $sum = count($ch);
            foreach ($ch as $key => $one) {
                $teacher = ZProblemNum::_getTeacherOne($one);
                $username .= $teacher['teacher_name'];
                if (($sum - 1) != $key) {
                    $username .= "、";
                }
            }
        }
        $this->renderPartial("allproblemuser", array('user_id' => $ch, 'username' => $username), true);
    }

    /*
     * 修改全通证号密码
     */

    public function actionProblemaccount() {
        if (isset($_POST) && !empty($_POST)) {

            $user_sn = $_POST['teacher_num'];
            $user_pwd = $_POST['teacher_pswd'];

            if (isset($_POST['allsubmit'])) {
                $sum = array();
                $start_str = $end_str = '';
                $a = substr_count($_POST['teacher_num'], '(*)');
                if ($a > 0) {
                    $strlen_b = strlen($_POST['teacher_num']);
                    $strlen_a = strlen('(*)');
                    $aa = strpos($_POST['teacher_num'], '(*)');
                    $start_str = substr($_POST['teacher_num'], 0, $aa);
                    $end_str = substr($_POST['teacher_num'], $aa + $strlen_a, $strlen_b);
                }
                if ($_POST['gz'] == 1) {
                    for ($i = $_POST['start']; $i <= $_POST['end']; $i++) {
                        $nn = '';
                        for ($j = 1; $j <= $_POST['length'] - strlen($i); $j++) {
                            $nn = "0" . $nn;
                        }
                        $sum[] = $start_str . $nn . $i . $end_str;
                    }
                } else {
                    $str = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
                    for ($i = strpos($str, $_POST['astart']); $i <= strrpos($str, $_POST['aend']); $i++) {
                        $sum[] = $start_str . $str[$i] . $end_str;
                    }
                }
                if ($_POST['user_id']) {
                    foreach ($_POST['user_id'] as $key => $one) {
                        $teacher = new Teacher();
                        $teacherinfo = $teacher->findByPk($one);
                        $teacherinfo->teacher_num = isset($sum[$key]) ? $sum[$key] : '';
                        $teacherinfo->teacher_pswd = $user_pwd;
                        $teacherinfo->save();
                    }
                    $this->redirect('/problem/default/list');
                }
            } else if (isset($_POST['onesubmit'])) {
                if ($_POST['id']) {
                    $teacher = new Teacher();
                    $teacherinfo = $teacher->findByPk($_POST['id']);
                    $teacherinfo->teacher_num = $user_sn;
                    $teacherinfo->teacher_pswd = $user_pwd;
                    $teacherinfo->save();
                    $this->redirect('/problem/default/list');
                }
            }
            $this->runShowMessge("/problem/default/list", "全通账户号生成失败");
        }
    }

    //全通帐号全部生成页面
    public function actionAllproblemuserall() {
        $exam_id = (int) $this->request->getParam('exam_id');
        $subject_id = (int) $this->request->getParam('subject_id');
        $school_id = (int) $this->request->getParam('school_id');
        $username = (string) $this->request->getParam('username');
        $this->renderPartial("allproblemuserall", array('exam_id' => $exam_id, 'subject_id' => $subject_id, 'school_id' => $school_id, 'username' => $username), true);
    }

    /*
     * 全部生成全通证号密码
     */

    public function actionProblemaccountall() {

        $exam_id = (int) $this->request->getParam('exam_id');
        $subject_id = (int) $this->request->getParam('subject_id');
        $school_id = (int) $this->request->getParam('school_id');
        $username = (string) $this->request->getParam('username');
        $where = " WHERE 1=1 ";
        $sql = ' SELECT "teacher_id" FROM "{{teacher}}" ';
        if (isset($exam_id) && !empty($exam_id) > 0) {
            $where.= ' AND "exam_id" = ' . $exam_id;
        }
        if (isset($subject_id) && !empty($subject_id) > 0) {
            $where.= ' AND "subject_id" = ' . $subject_id;
        }
        if (isset($school_id) && !empty($school_id) > 0) {
            $where.= ' AND "school_id" = ' . $school_id;
        }
        if (isset($username) && !empty($username)) {
            $where.= ' AND "teacher_name" LIKE \'%' . $username . '%\'';
        }
        $data = Yii::app()->db->createCommand($sql . $where)->queryAll();
        $user_sn = $_POST['teacher_num'];
        $user_pwd = $_POST['teacher_pswd'];
        $sum = array();
        $start_str = $end_str = '';
        $a = substr_count($_POST['teacher_num'], '(*)');
        if ($a > 0) {
            $strlen_b = strlen($_POST['teacher_num']);
            $strlen_a = strlen('(*)');
            $aa = strpos($_POST['teacher_num'], '(*)');
            $start_str = substr($_POST['teacher_num'], 0, $aa);
            $end_str = substr($_POST['teacher_num'], $aa + $strlen_a, $strlen_b);
        }
        if ($_POST['gz'] == 1) {
            for ($i = $_POST['start']; $i <= $_POST['end']; $i++) {
                $nn = '';
                for ($j = 1; $j <= $_POST['length'] - strlen($i); $j++) {
                    $nn = "0" . $nn;
                }
                $sum[] = $start_str . $nn . $i . $end_str;
            }
        } else {
            $str = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
            for ($i = strpos($str, $_POST['astart']); $i <= strrpos($str, $_POST['aend']); $i++) {
                $sum[] = $start_str . $str[$i] . $end_str;
            }
        }
        if ($data) {
            foreach ($data as $key => $one) {
                $teacher = new Teacher();
                $teacherinfo = $teacher->findByPk($one['teacher_id']);
                $teacherinfo->teacher_num = isset($sum[$key]) ? $sum[$key] : '';
                $teacherinfo->teacher_pswd = $user_pwd;
                $teacherinfo->save();
            }
            $this->redirect('/problem/default/list');
        }
        $this->runShowMessge("/problem/default/list", "全通账户号生成失败");
    }

    /*
     * 导出
     */

    public function actionOutlist() {
        $this->__common();
        $this->title = "全通信息导出";
        $wh = '';
        //权限判断
        if ($this->user_role_list != 1 && !empty($this->exam_id)) {
            $wh = " AND \"exam_id\" IN (" . $this->exam_id . ")";
        }
        $data['exam'] = ZTask::_getExamAll($wh);
        $schoolwhere = ' WHERE "is_del" = 0';
        $data['school'] = Nojoin::_getschoolAll($schoolwhere);
        $subjectwhere = ' WHERE "is_del"=0 ';
        $data['subject'] = Nojoin::_getsubjectAll($subjectwhere);
        $problemwhere = ' WHERE "is_show" = 1 ';
        $data['problemrule'] = ZTask::_getproblemrule($problemwhere);
        $this->render('outlist', array('data' => $data));
    }
	
	
	public function actionExports(){
		if(!empty($_POST['submit'])){
		
		
		
		
			exit;
			$info = $this->request->getParam('info');
			if(isset($info['school']) && !empty($info['school'])){
				$school = '';
				foreach($info['school'] as $sk=>$sv){
					$school.= "&info[school][]=".$sv;
				}
			}else{   
                                 $this->frameAjaxMessage(null, "必须选择一个学校");exit;
			}
			 //得到科目信息**************************************************************************************************************
			if(isset($info['subject']) && !empty($info['subject'])){
				foreach ($info['subject'] as $subk => $subv) {
					echo "<iframe frameborder='0' src='/problem/default/export?submit=1&info[exam_id]=".$info['exam_id']."&info[exam_name]=".$info['exam_name']."&info[problem_id]=".$info['problem_id']."&info[subject][]=".$subv.$school."'></iframe>";
				}
			}else{
                                 $this->frameAjaxMessage(null, "必须选择一个学校"); exit;
			}	
		}else{
                         $this->frameAjaxMessage(null, "不是提交来的数据"); exit;
		}
	}

    public function actionExport() {

        if (!empty($_POST['submit']) || !empty($_GET['submit'])) {
            $info = $this->request->getParam('info');
			
            if (!empty($info['exam_id']) && !empty($info['problem_id']) && !empty($info['school']) && !empty($info['subject'])) {
                //得到项目信息
                $examwhere = ' AND "exam_id" =' . $info['exam_id'];
                $exam = ZTask::_getExamAll($examwhere);
                //得到全通导出规则
                $problemrulewhere = ' WHERE "id" =' . $info['problem_id'];
                $problemrule = ZTask::_getproblemrule($problemrulewhere);
                if (empty($problemrule)) {
                    $this->frameAjaxMessage("/problem/rules/index", "全通规则为空");
                    exit;
                }
				$is_exam = $problemrule[0]['is_exam'];
				
		
                //得到全通导出规则明细
                $problemruledetailwhere = ' WHERE "id" > 0 AND "problemrule_id" =' . $info['problem_id'].' ORDER BY TO_NUMBER("number") ASC ';
                $problemrule_detail = ZProblemNum::_getAllproblemrule_detail($problemruledetailwhere);
                if (empty($problemrule_detail)) {
                    $this->frameAjaxMessage(null, "请设定该项导出全通规则的详情信息");
                    exit;
                }
				
                if (!isset($info['is_sheet'])) {
                    //得到科目信息
                    $subjectid = implode(',', $info['subject']);
                    $subjectwhere = ' WHERE "subject_id" IN (' . $subjectid . ')';
                    $subjectnames = Nojoin::_getsubjectAll($subjectwhere);
                    $subjectname = array();
                    foreach ($subjectnames as $k => $v) {
                        $subjectname[] = $v['subject_name'];
                    }

                    $subjectname = implode("-", $subjectname);
                    //得到学校信息
                    $schoolid = implode(',', $info['school']);
                    $title = $problemrule[0]['name'];
                    if (strstr($problemrule[0]['name'], '学生')) {
                        $title = '参加考试学生名单';
                    }
                    if (strstr($problemrule[0]['name'], '教师')) {
                        $title = $exam[0]['exam_term_name'] . '+阅卷教师名单-' . $subjectname;
                    }
                    if (strstr($problemrule[0]['name'], '文件')) {
                        $title = $exam[0]['exam_term_name'] . '+扫描文件-' . $subjectname;
                    }
                    $zimu = array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G', 7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N', 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U', 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'W', 25 => 'Y', 26 => 'Z');
                    spl_autoload_unregister(array('YiiBase', 'autoload'));
                    include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
                    include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');
                    $objPHPExcel = new PHPExcel();

                    $objPHPExcel->setActiveSheetIndex(0);
                    $objActSheet = $objPHPExcel->getActiveSheet();
                    foreach ($problemrule_detail as $k => $v) {
                        $objActSheet->setCellValue($zimu[$k] . '1', $v['name']);
                        $objActSheet->getColumnDimension($zimu[$k])->setWidth(16);
                    }
                    //$data = null;
                    if ($problemrule[0]['sqlname'] == 'teacher') {
                        $sql = 'SELECT * FROM "{{' . $problemrule[0]['sqlname'] . '}}" WHERE "exam_id" = ' . $info['exam_id'] . ' AND "school_id" IN(' . $schoolid . ') AND "subject_id" IN(' . $subjectid . ')';
                    }
                    if ($problemrule[0]['sqlname'] == 'student') {
				
                        $sql = "SELECT distinct(student.\"student_id\"),student.* 
                                        FROM \"{{student}}\" student  
                                        LEFT JOIN  \"{{point}}\" point  ON point.\"number\" = \"exam_code\" 
                                        WHERE point.\"subject_id\" IN({$subjectid}) 
                                        AND point.\"exam_id\" = '{$info['exam_id']}'
                                        AND student.\"school_id\" IN ({$schoolid})";
                        if(empty($problemrule[0]['is_exam'])){
                            //$sql .= ' AND ("exam_code" = \'\' OR "exam_code" IS NULL) ';
                        }
                        $sql .= "ORDER BY student.\"school_id\", student.\"exam_code\" ASC";
                    }
					
                    $data = Yii::app()->db->createcommand($sql)->queryAll();
					//   考号为空的数据
					$nullData = array();
				
					if(!empty($is_exam) && $problemrule[0]['sqlname'] == 'student'){
						$nullSql = 'SELECT * FROM "{{student}}" WHERE "exam_code" IS NULL AND "exam_id" = '.$info['exam_id'].' AND "school_id" IN('.$schoolid.') ORDER BY "school_id" ASC';
						$nullData = Yii::app()->db->createcommand($nullSql)->queryAll();
						if(!empty($nullData)){
							$data = array_merge($data,$nullData);
						}
					}
		/* 			print_r($data);exit; */
                    $objPHPExcel->setActiveSheetIndex(0);
                    $objActSheet = $objPHPExcel->getActiveSheet();
                    $i = 2;
                    foreach ($data as $k => $v) {
                        foreach ($problemrule_detail as $p => $d) {

                            $rowvalue = '';
                            if ($d['out_name'] == 'gdz') {
                                $rowvalue = $d['value'];
                            }elseif($d['out_name'] == 'exam_id'){
								if(isset($info['exam_name']) && !empty($info['exam_name'])){
									$rowvalue = $info['exam_name'];
								}else{
									$rowvalue = $exam[0]['exam_term_name'];
								}
							}else{
                                if ($d['out_name'] == 'student_sex') {
                                    if ($v[$d['out_name']] == 1) {
                                        $rowvalue = '男';
                                    } elseif ($v[$d['out_name']] == 2) {
                                        $rowvalue = '女';
                                    } else {
                                        $rowvalue = '';
                                    }
                                } else {
                                    $rowvalue = $v[$d['out_name']];
                                }
                            }
                            if ($d['out_name'] == 'roll') {
                                $rowvalue = ' ' . $rowvalue;
                            }
                            $objActSheet->setCellValue($zimu[$p] . $i, $rowvalue);
                        }
                        $i++;
                    };
                    $objPHPExcel->setActiveSheetIndex(0);
                   
                    $ua = $_SERVER["HTTP_USER_AGENT"];
                    $file_nams = $title;
                    $file_nams .= ".xls";
     
	     		  ob_end_clean();
                    header("Content-Type: application/vnd.ms-excel;charset=utf-8");
                    $encoded_filename = urlencode($file_nams);
                    $encoded_filename = str_replace("+", "%20", $encoded_filename);
                    header('Content-Type: application/octet-stream');
                    if (preg_match("/MSIE/", $ua)) {
                        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
                    } else if (preg_match("/Firefox/", $ua)) {
                        header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_nams . '"');
                    } else {
                        header('Content-Disposition: attachment; filename="' . $file_nams . '"');
                    }
                    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
                    header('Expires:0');
                    header('Pragma:public');
                    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                    $objWriter->save('php://output');
					
                    Yii::app()->end();
                    spl_autoload_register(array('YiiBase', 'autoload'));
					unset($objPHPExcel);
                    exit();
                } else {
                   //得到科目信息**************************************************************************************************************
					$path = UPLOAD_PATH.'/quantong/'.time();
					if(!file_exists($path)){
						mkdir($path,0777,true);
					}
					
					
                    foreach ($info['subject'] as $subk => $subv) {

                        $subjectid = $subv;
                        $subjectwhere = ' WHERE "subject_id" IN (' . $subjectid . ')';
                        $subjectnames = Nojoin::_getsubjectAll($subjectwhere);
					
                        $subjectname = array();
						$subject_code = array();
                        foreach ($subjectnames as $k => $v) {
                            $subjectname[] = $v['subject_name'];
							$subject_code[] = $v['subject_code'];
                        }
						$subject_code = implode("-", $subject_code);
                        $subjectname = implode("-", $subjectname);
                        //得到学校信息
                        $schoolid = implode(',', $info['school']);
                        $title = $problemrule[0]['name'];
                        if (strstr($problemrule[0]['name'], '学生')) {
                            $title = '参加考试学生名单';
                        }
                        if (strstr($problemrule[0]['name'], '教师')) {
                            $title = $exam[0]['exam_term_name'] . '+阅卷教师名单-' . $subjectname;
                        }
                        if (strstr($problemrule[0]['name'], '文件')) {
                            $title = $exam[0]['exam_term_name'] . '+扫描文件-' . $subjectname;
                        }


                        $zimu = array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G', 7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N', 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U', 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'W', 25 => 'Y', 26 => 'Z');
                        spl_autoload_unregister(array('YiiBase', 'autoload'));
                        if ($subk == 0) {
                            include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
                            include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');
                            //$objPHPExcel = new PHPExcel();
                        }
						$objPHPExcel = new PHPExcel();
						include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPZip.class.php');
                        $objPHPExcel->setActiveSheetIndex(0);
                        $objActSheet = $objPHPExcel->getActiveSheet();

                        foreach ($problemrule_detail as $k => $v) {
                            $objActSheet->setCellValue($zimu[$k] . '1', $v['name']);
                            $objActSheet->getColumnDimension($zimu[$k])->setWidth(16);
                        }
                        if ($problemrule[0]['sqlname'] == 'teacher') {
                            $sql = 'SELECT * FROM "{{' . $problemrule[0]['sqlname'] . '}}" WHERE "exam_id" = ' . $info['exam_id'] . ' AND "school_id" IN(' . $schoolid . ') AND "subject_id" IN(' . $subjectid . ')';
                        }
                        if ($problemrule[0]['sqlname'] == 'student') {
                        	$sql = "SELECT distinct(student.\"student_id\"),student.* 
                                        FROM \"{{student}}\" student  
                                        LEFT JOIN  \"{{point}}\" point  ON point.\"number\" = \"exam_code\" 
                                        WHERE point.\"subject_id\" IN({$subjectid}) 
                                        AND point.\"exam_id\" = '{$info['exam_id']}'
                                        AND student.\"school_id\" IN ({$schoolid})";
                    	
                            $sql .= "ORDER BY student.\"school_id\", student.\"exam_code\" ASC";
                        }
						
                        $data = Yii::app()->db->createcommand($sql)->queryAll();
						/* print_r($data);
						echo "<hr>";
						continue; */
						$studentData = array();
						$disciplinData = array();
						if(!empty($is_exam)){
								
								$nullSql = "SELECT aa.\"disciplin_nick\" FROM \"{{disciplin_subject}}\" bb LEFT JOIN \"{{disciplin}}\" aa ON aa.\"disciplin_id\" = bb.\"disciplin_id\"  WHERE \"subject_id\" IN({$subjectid}) ";
								$disciplinData = Yii::app()->db->createcommand($nullSql)->queryAll();
								
								$disciplin_string = '';
								if(!empty($disciplinData)){
										
									foreach($disciplinData as $dk=>$dv){
										$disciplin_string.= "'".$dv['disciplin_nick']."',";
									}	
									$disciplin_string.="'0'";
									$disciplinSql = "SELECT * FROM \"{{student}}\" WHERE \"disciplin_name\" IN({$disciplin_string}) AND \"exam_id\" = '{$info['exam_id']}' AND \"school_id\" IN ({$schoolid}) AND \"exam_code\" IS NULL ";
								}else{
									$disciplinSql = "SELECT * FROM \"{{student}}\" WHERE \"exam_id\" = '{$info['exam_id']}' AND \"school_id\" IN ({$schoolid}) AND \"exam_code\" IS NULL ";
								}
								$studentData = Yii::app()->db->createcommand($disciplinSql)->queryAll();
						}
					
						if(!empty($studentData) && !empty($data)){
						
							$data = array_merge($data,$studentData);
						}
                        $objPHPExcel->setActiveSheetIndex(0);
                        $objActSheet = $objPHPExcel->getActiveSheet();
                      
                        $i = 2;
						
                        if (!empty($data)) {

                            foreach ($data as $k => $v) {

                                foreach ($problemrule_detail as $p => $d) {

                                    $rowvalue = '';
                                    if ($d['out_name'] == 'gdz') {
                                        $rowvalue = $d['value'];
                                    }elseif($d['out_name'] == 'exam_id'){
										if(isset($info['exam_name']) && !empty($info['exam_name'])){
											$rowvalue = $info['exam_name'];
										}else{
											$rowvalue = $exam[0]['exam_term_name'];
										}
									} else {
                                        if ($d['out_name'] == 'student_sex') {
                                            if ($v[$d['out_name']] == 1) {
                                                $rowvalue = '男';
                                            } elseif ($v[$d['out_name']] == 2) {
                                                $rowvalue = '女';
                                            } else {
                                                $rowvalue = '';
                                            }
                                        } else {
                                            $rowvalue = $v[$d['out_name']];
                                        }
                                    }
                                    if ($d['out_name'] == 'roll') {
                                        $rowvalue = ' ' . $rowvalue;
                                    }
                                    $objActSheet->setCellValue($zimu[$p] . $i, $rowvalue);
                                }
                                $i++;
                            }
                        }
                        $objPHPExcel->setActiveSheetIndex(0);
						
						$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
						$subjectname = iconv("UTF-8","gb2312",$subjectname);
						$objWriter->save($path.'/'.$subjectname.'.xls');
						unset($objPHPExcel);
                    }
	
					$zip = new PHPZip();
					$zip->ZipAndDownload($path,$title);
					$this->delete_dir($path);
					ob_end_clean();
					exit;
                  
                    ob_end_clean();
                    $ua = $_SERVER["HTTP_USER_AGENT"];
                    $file_nams = $title;
                    $file_nams .= ".xls";
            
                    header("Content-Type: application/vnd.ms-excel;charset=utf-8");
                    $encoded_filename = urlencode($file_nams);
                    $encoded_filename = str_replace("+", "%20", $encoded_filename);
                    header('Content-Type: application/octet-stream');
                    if (preg_match("/MSIE/", $ua)) {
                        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
                    } else if (preg_match("/Firefox/", $ua)) {
                        header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_nams . '"');
                    } else {
                        header('Content-Disposition: attachment; filename="' . $file_nams . '"');
                    }
                    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
                    header('Expires:0');
                    header('Pragma:public');
            
                    Yii::app()->end();
                    spl_autoload_register(array('YiiBase', 'autoload'));
                    exit();
                }
            } else {
                $this->runShowMessge("/problem/default/outlist/", "考试项目,导出规则,学校,科目为必选项");
            }
        } else {
            $this->runShowMessge("/problem/default/outlist/", "不是提交来的数据");
        }
    }
   
   
   
   
   
   
   
   
   // 要再改回这种方式,我就问候你全家.
    public function actionExport_bak() {

        if (!empty($_POST['submit']) || !empty($_GET['submit'])) {
            $info = $this->request->getParam('info');
			
            if (!empty($info['exam_id']) && !empty($info['problem_id']) && !empty($info['school']) && !empty($info['subject'])) {
                //得到项目信息
                $examwhere = ' AND "exam_id" =' . $info['exam_id'];
                $exam = ZTask::_getExamAll($examwhere);
                //得到全通导出规则
                $problemrulewhere = ' WHERE "id" =' . $info['problem_id'];
                $problemrule = ZTask::_getproblemrule($problemrulewhere);
                if (empty($problemrule)) {
                    $this->runShowMessge("/problem/rules/index", "全通规则为空");
                    exit;
                }
                //得到全通导出规则明细
                $problemruledetailwhere = ' WHERE "id" > 0 AND "problemrule_id" =' . $info['problem_id'].' ORDER BY TO_NUMBER("number") ASC ';
                $problemrule_detail = ZProblemNum::_getAllproblemrule_detail($problemruledetailwhere);
                if (empty($problemrule_detail)) {
                    $this->runShowMessge("/problem/rules/index", "你没有设置任何导出全通规则详情,所以你是导不出任何数据的");
                    exit;
                }
				
                if (!isset($info['is_sheet'])) {
                    //得到科目信息
                    $subjectid = implode(',', $info['subject']);
                    $subjectwhere = ' WHERE "subject_id" IN (' . $subjectid . ')';
                    $subjectnames = Nojoin::_getsubjectAll($subjectwhere);
                    $subjectname = array();
                    foreach ($subjectnames as $k => $v) {
                        $subjectname[] = $v['subject_name'];
                    }

                    $subjectname = implode("-", $subjectname);
                    //得到学校信息
                    $schoolid = implode(',', $info['school']);
                    $title = $problemrule[0]['name'];
                    if (strstr($problemrule[0]['name'], '学生')) {
                        $title = '参加考试学生名单';
                    }
                    if (strstr($problemrule[0]['name'], '教师')) {
                        $title = $exam[0]['exam_term_name'] . '+阅卷教师名单-' . $subjectname;
                    }
                    if (strstr($problemrule[0]['name'], '文件')) {
                        $title = $exam[0]['exam_term_name'] . '+扫描文件-' . $subjectname;
                    }
                    $zimu = array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G', 7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N', 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U', 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'W', 25 => 'Y', 26 => 'Z');
                    spl_autoload_unregister(array('YiiBase', 'autoload'));
                    include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
                    include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');
                    $objPHPExcel = new PHPExcel();

                    $objPHPExcel->setActiveSheetIndex(0);
                    $objActSheet = $objPHPExcel->getActiveSheet();
                    foreach ($problemrule_detail as $k => $v) {
                        $objActSheet->setCellValue($zimu[$k] . '1', $v['name']);
                        $objActSheet->getColumnDimension($zimu[$k])->setWidth(16);
                    }
                    //$data = null;
                    if ($problemrule[0]['sqlname'] == 'teacher') {
                        $sql = 'SELECT * FROM "{{' . $problemrule[0]['sqlname'] . '}}" WHERE "exam_id" = ' . $info['exam_id'] . ' AND "school_id" IN(' . $schoolid . ') AND "subject_id" IN(' . $subjectid . ')';
                    }
                    if ($problemrule[0]['sqlname'] == 'student') {
                        $sql = "SELECT distinct(student.\"student_id\"),student.* 
                                        FROM \"{{student}}\" student  
                                        LEFT JOIN  \"{{point}}\" point  ON point.\"number\" = \"exam_code\" 
                                        WHERE point.\"subject_id\" IN({$subjectid}) 
                                        AND point.\"exam_id\" = '{$info['exam_id']}'
                                        AND student.\"school_id\" IN ({$schoolid})";
                        if(isset($problemrule[0]['is_exam']) && $problemrule[0]['is_exam']!=1){
                            $sql .= ' AND ("exam_code" != \'\' OR "exam_code" IS NOT NULL) ';
                        }
                        $sql .= "ORDER BY student.\"school_id\", student.\"exam_code\" ASC";
                    }
                    
                   $data = Yii::app()->db->createcommand($sql)->queryAll();
                    $objPHPExcel->setActiveSheetIndex(0);
                    $objActSheet = $objPHPExcel->getActiveSheet();
                    $i = 2;
                    foreach ($data as $k => $v) {
                        foreach ($problemrule_detail as $p => $d) {

                            $rowvalue = '';
                            if ($d['out_name'] == 'gdz') {
                                $rowvalue = $d['value'];
                            }elseif($d['out_name'] == 'exam_id'){
								if(isset($info['exam_name']) && !empty($info['exam_name'])){
									$rowvalue = $info['exam_name'];
								}else{
									$rowvalue = $exam[0]['exam_term_name'];
								}
							}else{
                                if ($d['out_name'] == 'student_sex') {
                                    if ($v[$d['out_name']] == 1) {
                                        $rowvalue = '男';
                                    } elseif ($v[$d['out_name']] == 2) {
                                        $rowvalue = '女';
                                    } else {
                                        $rowvalue = '';
                                    }
                                } else {
                                    $rowvalue = $v[$d['out_name']];
                                }
                            }
                            if ($d['out_name'] == 'roll') {
                                $rowvalue = ' ' . $rowvalue;
                            }
                            $objActSheet->setCellValue($zimu[$p] . $i, $rowvalue);
                        }
                        $i++;
                    };
                    $objPHPExcel->setActiveSheetIndex(0);
                    ob_end_clean();
                    $ua = $_SERVER["HTTP_USER_AGENT"];
                    $file_nams = $title;
                    $file_nams .= ".xls";
                    /*
                      if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
                      $file_nams = urlencode($file_nams);
                      $file_nams = str_replace("+", "%20", $file_nams); // 替换空格
                      }
                     */
                    header("Content-Type: application/vnd.ms-excel;charset=utf-8");
                    $encoded_filename = urlencode($file_nams);
                    $encoded_filename = str_replace("+", "%20", $encoded_filename);
                    header('Content-Type: application/octet-stream');
                    if (preg_match("/MSIE/", $ua)) {
                        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
                    } else if (preg_match("/Firefox/", $ua)) {
                        header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_nams . '"');
                    } else {
                        header('Content-Disposition: attachment; filename="' . $file_nams . '"');
                    }
                    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
                    header('Expires:0');
                    header('Pragma:public');
                    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                    $objWriter->save('php://output');
                    Yii::app()->end();
                    spl_autoload_register(array('YiiBase', 'autoload'));
                    exit();
                } else {

                    //得到科目信息**************************************************************************************************************
                    foreach ($info['subject'] as $subk => $subv) {

                        $subjectid = $subv;
                        $subjectwhere = ' WHERE "subject_id" IN (' . $subjectid . ')';
                        $subjectnames = Nojoin::_getsubjectAll($subjectwhere);
                        $subjectname = array();
                        foreach ($subjectnames as $k => $v) {
                            $subjectname[] = $v['subject_name'];
                        }

                        $subjectname = implode("-", $subjectname);
                        //得到学校信息
                        $schoolid = implode(',', $info['school']);
                        $title = $problemrule[0]['name'];
                        if (strstr($problemrule[0]['name'], '学生')) {
                            $title = '参加考试学生名单';
                        }
                        if (strstr($problemrule[0]['name'], '教师')) {
                            $title = $exam[0]['exam_term_name'] . '+阅卷教师名单-' . $subjectname;
                        }
                        if (strstr($problemrule[0]['name'], '文件')) {
                            $title = $exam[0]['exam_term_name'] . '+扫描文件-' . $subjectname;
                        }


                        $zimu = array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G', 7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N', 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U', 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'W', 25 => 'Y', 26 => 'Z');
                        spl_autoload_unregister(array('YiiBase', 'autoload'));
                        if ($subk == 0) {
                            include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
                            include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');
                            $objPHPExcel = new PHPExcel();
                        }
                        $objPHPExcel->createSheet();      // 创建sheet
                        $objPHPExcel->setActiveSheetIndex($subk);
                        $objActSheet = $objPHPExcel->getActiveSheet();

                        foreach ($problemrule_detail as $k => $v) {
                            $objActSheet->setCellValue($zimu[$k] . '1', $v['name']);
                            $objActSheet->getColumnDimension($zimu[$k])->setWidth(16);
                        }
                        if ($problemrule[0]['sqlname'] == 'teacher') {
                            $sql = 'SELECT * FROM "{{' . $problemrule[0]['sqlname'] . '}}" WHERE "exam_id" = ' . $info['exam_id'] . ' AND "school_id" IN(' . $schoolid . ') AND "subject_id" IN(' . $subjectid . ')';
                        }
                        if ($problemrule[0]['sqlname'] == 'student') {
                        	$sql = "SELECT distinct(student.\"student_id\"),student.* 
                                        FROM \"{{student}}\" student  
                                        LEFT JOIN  \"{{point}}\" point  ON point.\"number\" = \"exam_code\" 
                                        WHERE point.\"subject_id\" IN({$subjectid}) 
                                        AND point.\"exam_id\" = '{$info['exam_id']}'
                                        AND student.\"school_id\" IN ({$schoolid})";
                            if(isset($problemrule[0]['is_exam']) && $problemrule[0]['is_exam']!=1){
                                $sql .= ' AND ("exam_code" != \'\' OR "exam_code" IS NOT NULL) ';
                            }
                            $sql .= "ORDER BY student.\"school_id\", student.\"exam_code\" ASC";
                        }
 
                        $data[$subk] = Yii::app()->db->createcommand($sql)->queryAll();
                        $objPHPExcel->setActiveSheetIndex($subk);
                        $objActSheet = $objPHPExcel->getActiveSheet();
                        $objActSheet->setTitle($subjectname);   // 命名sheet
                        $i = 2;


                        if (!empty($data[$subk])) {

                            foreach ($data[$subk] as $k => $v) {

                                foreach ($problemrule_detail as $p => $d) {

                                    $rowvalue = '';
                                    if ($d['out_name'] == 'gdz') {
                                        $rowvalue = $d['value'];
                                    }elseif($d['out_name'] == 'exam_id'){
										if(isset($info['exam_name']) && !empty($info['exam_name'])){
											$rowvalue = $info['exam_name'];
										}else{
											$rowvalue = $exam[0]['exam_term_name'];
										}
									} else {
                                        if ($d['out_name'] == 'student_sex') {
                                            if ($v[$d['out_name']] == 1) {
                                                $rowvalue = '男';
                                            } elseif ($v[$d['out_name']] == 2) {
                                                $rowvalue = '女';
                                            } else {
                                                $rowvalue = '';
                                            }
                                        } else {
                                            $rowvalue = $v[$d['out_name']];
                                        }
                                    }
                                    if ($d['out_name'] == 'roll') {
                                        $rowvalue = ' ' . $rowvalue;
                                    }
                                    $objActSheet->setCellValue($zimu[$p] . $i, $rowvalue);
                                }
                                $i++;
                            }
                        }
                        $objPHPExcel->setActiveSheetIndex($subk);
                    }
                
                   // ob_end_clean();
                   // header("Content-Type: application/vnd.ms-excel;charset=utf-8");
                   //header("Content-Disposition: attachment; filename=" . $file_nams);
                    ob_end_clean();
                    $ua = $_SERVER["HTTP_USER_AGENT"];
                    $file_nams = $title;
                    $file_nams .= ".xls";
                    /*
                      if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
                      $file_nams = urlencode($file_nams);
                      $file_nams = str_replace("+", "%20", $file_nams); // 替换空格
                      }
                     */
                    header("Content-Type: application/vnd.ms-excel;charset=utf-8");
                    $encoded_filename = urlencode($file_nams);
                    $encoded_filename = str_replace("+", "%20", $encoded_filename);
                    header('Content-Type: application/octet-stream');
                    if (preg_match("/MSIE/", $ua)) {
                        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
                    } else if (preg_match("/Firefox/", $ua)) {
                        header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_nams . '"');
                    } else {
                        header('Content-Disposition: attachment; filename="' . $file_nams . '"');
                    }
                    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
                    header('Expires:0');
                    header('Pragma:public');
                    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                    $objWriter->save('php://output');
                    Yii::app()->end();
                    spl_autoload_register(array('YiiBase', 'autoload'));
                    exit();
                }
            } else {
                $this->frameAjaxMessage(null, "考试项目,导出规则,学校,科目为必选项");exit;
            }
        } else {
            $this->frameAjaxMessage(null, "不是提交来的数据");exit;
        }
    }

    /**
     * @ 批量删除学段
     * @ yindebin
     * @ 2014-01-06 pm
     *
     */
    public function actionDelete_all() {
        $id = Yii::app()->request->getparam('id');
        if (!empty($id)) {
            $delete = 'DELETE FROM "{{teacher}}" WHERE "teacher_id" IN (' . $id . ')';
            $query = Yii::app()->db->createCommand($delete)->execute();
            echo 1;
        } else {
            echo 2;
        }
    }

	
	public function delete_dir($dir_name){
		// 打开目录
		$handle = opendir($dir_name);
		//滤掉 "." 和 ".."目录
		readdir($handle);
		readdir($handle);
		//遍历目录文件
		while (($file=readdir($handle))!==FALSE){
			// 子目录
			$file = $dir_name.DIRECTORY_SEPARATOR.$file;
			//判断是否为目录
			if(is_dir($file)){
				//递归调用
				delete_dir($file);
			}else {
				//删除文件
				@unlink($file);
			}
		}
		//关闭
		closedir($handle);
		//删除目录
		@rmdir($dir_name);
	}
	
}